package lch.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import lch.constant.MessageConstant;
import lch.entity.Result;
import lch.service.MemberService;
import lch.service.ReportService;
import lch.service.SetmealService;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author lch
 * @date 2019-12-26 16:41
 */
@RestController
@RequestMapping("/report")
public class ReportController {
    @Reference
    private MemberService memberService;
    @Reference
    private SetmealService setmealService;
    @Reference
    private ReportService reportService;

    @RequestMapping("/getMemberReport")
    public Result getMemberReport() {
        //获得日历对象
        Calendar calendar = Calendar.getInstance();
        List<String> months = new ArrayList();
        calendar.add(Calendar.MONTH, -12);
        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH, 1);
            Date date = calendar.getTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM");
            String format_date = sdf.format(date);
            months.add(format_date);
        }
        List<Integer> memberCountByMonths = memberService.findMemberCountByMonths(months);
        Map<String, Object> map = new HashMap<>();
        map.put("months", months);
        map.put("memberCount", memberCountByMonths);
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
    }

    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport() {
        Map<String, Object> map = new HashMap<>();
        try {
            List<Map<String, Object>> list = setmealService.findSetmealCount();
            map.put("setmealCount", list);
            List<String> stringList = new ArrayList<>();
            for (Map<String, Object> stringObjectMap : list) {
                String name = (String) stringObjectMap.get("name");
                stringList.add(name);
            }
            map.put("setmealNames", stringList);
            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData() {
        try {
            Map<String, Object> map = reportService.getBusinessReportData();
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletResponse response, HttpServletRequest request) {
        try {
            //获取map里的数据
            Map<String, Object> map = reportService.getBusinessReportData();
            String reportDate = (String) map.get("reportDate");
            Integer todayNewMember = (Integer) map.get("todayNewMember");
            Integer totalMember = (Integer) map.get("totalMember");
            Integer thisWeekNewMember = (Integer) map.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) map.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) map.get("todayOrderNumber");
            Integer todayVisitsNumber = (Integer) map.get("todayVisitsNumber");
            Integer thisWeekOrderNumber = (Integer) map.get("thisWeekOrderNumber");
            Integer thisWeekVisitsNumber = (Integer) map.get("thisWeekVisitsNumber");
            Integer thisMonthOrderNumber = (Integer) map.get("thisMonthOrderNumber");
            Integer thisMonthVisitsNumber = (Integer) map.get("thisMonthVisitsNumber");
            List<Map> hotSetmeal = (List<Map>) map.get("hotSetmeal");

            String realPath = request.getSession().getServletContext().getRealPath("template" + File.separator + "report_template.xlsx");
            //获取文件
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(realPath)));
            //获取表1
            XSSFSheet sheet = workbook.getSheetAt(0);
            //填入日期
            XSSFRow row = sheet.getRow(2);
            XSSFCell cell = row.getCell(5);
            cell.setCellValue(reportDate);

            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);//新增会员数（本日）
            row.getCell(7).setCellValue(totalMember);//总会员数
            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数
            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数
            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数
            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

            int row_hot = 12;
            for (Map mapInhotSetmeal : hotSetmeal) {
                String name = (String) mapInhotSetmeal.get("name");
                Long setmeal_count = (Long) mapInhotSetmeal.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) mapInhotSetmeal.get("proportion");
                XSSFRow row1 = sheet.getRow(row_hot++);
                row1.getCell(4).setCellValue(name);
                row1.getCell(5).setCellValue(setmeal_count);
                row1.getCell(6).setCellValue(proportion.doubleValue());
            }
            ServletOutputStream outputStream = response.getOutputStream();
            //响应回去类型和表头
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");
            response.setContentType("application/vnd.ms-excel");
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            workbook.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    /*@RequestMapping("/exportBusinessReport4PDF")
    public Result exportBusinessReport4PDF(HttpServletResponse response, HttpServletRequest request) {
        try {
            //获取map里的数据
            Map<String, Object> result = reportService.getBusinessReportData();
            //取出返回结果数据，准备将报表数据写入到PDF文件中
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");
            //动态获取模板文件绝对磁盘路径
            String jrxmlPath = request.getSession().getServletContext().getRealPath("template" + File.separator + "health_business3.jrxml");
            String jasperPath = request.getSession().getServletContext().getRealPath("template" + File.separator + "health_business3.jasper");
            //编译模板
            JasperCompileManager.compileReportToFile(jrxmlPath, jasperPath);
            //填充数据---使用JavaBean数据源方式填充
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath, result, new JRBeanCollectionDataSource(hotSetmeal));

            //响应回去类型和表头
            ServletOutputStream outputStream = response.getOutputStream();
            response.setHeader("content-Disposition", "attachment;filename=report.pdf");
            response.setContentType("application/pdf");

            //输出文件
            JasperExportManager.exportReportToPdfStream(jasperPrint,outputStream);

            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }*/
}
